package com.yeyks.wxcode.config;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author fuchangshuai
 * @date 2019/4/2 1:33 PM
 */
@Component
public class WxConfig {

    /**
     * 设置微信公众号的appid
     */
    private String appId = "wxfcdb77a8210d27ab";

    /**
     * 公众号的appSecret
     */
    private String appSecret = "a818f87ffa555a93621c17900a477bb5";

    //发送code获取openId信息
    private String getGzhOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private String getXcxOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    public Map<String, String> getWxModel(String type) {
        Map<String, String> map = new HashMap<>();
        /**
         * 小程序
         */
        if ("xcx".equals(type)) {
            appId = "wxcea0ee4d16192c35";
            appSecret = "42903a181a4a023c969b68fd9fc05090";
        }
        if ("wxpay".equals(type)) {
            appId = "wxdee60889e81703e8";
            appSecret = null;
        }
        if ("gzh".equals(type)) {
            appId = "wxfcdb77a8210d27ab";
            appSecret = "a818f87ffa555a93621c17900a477bb5";
        }
        map.put("appId", appId);
        map.put("appSecret", appSecret);
        if ("xcx".equals(type)) {
            map.put("url", getXcxOpenIdUrl);
        }
        if ("gzh".equals(type)) {
            map.put("url", getGzhOpenIdUrl);
        }
        return map;
    }

    @Bean
    public WxMpInMemoryConfigStorage initStorage() {
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(appId);
        config.setSecret(appSecret);
        return config;
    }

    @Bean
    public WxMpService initWxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(initStorage());
        return wxMpService;
    }

    /**
     * 获取发送code获取openId的链接
     *
     * @param type
     * @param code
     * @return
     */
    public String getOpenIdUrl(String type, String code) {
        Map<String, String> map = getWxModel(type);
        return String.format(map.get("url"), map.get("appId"), map.get("appSecret"), code);
    }

}
